﻿using Polly;
using System;
using System.Threading.Tasks;

namespace Cms.Core.Infrastructure.Helps
{
    /// <summary>
    /// 异常重试机制
    /// </summary>
    public static class PollyHelper
    {
        /// <summary>
        /// 执行重试
        /// </summary>
        /// <typeparam name="T">动态异常类型</typeparam>
        /// <param name="action">转入执行的方法</param>
        /// <param name="maxRetryAttmpts">重试次数</param>

        public static void WaitAndRetry<T>(Action action, int maxRetryAttmpts = 3) where T : Exception
        {

            var pauseBetweenFailures = TimeSpan.FromSeconds(2);

            var retryPolicy = Policy.Handle<T>().WaitAndRetry(maxRetryAttmpts, i => pauseBetweenFailures,
                (ex, t) => { action?.Invoke(); });
            retryPolicy.Execute(() => action?.Invoke());
        }

        public static async Task WaitAndRetryAsync<T>(Func<Task> func, int maxRetryAttmpts = 3) where T : Exception
        {

            var pauseBetweenFailures = TimeSpan.FromSeconds(2);

            var retryPolicy = Policy.Handle<T>().WaitAndRetryAsync(maxRetryAttmpts, i => pauseBetweenFailures,
                (ex, t) => { func?.Invoke(); });
            await retryPolicy.ExecuteAsync(() => func?.Invoke());
        }
    }
}
